import express from 'express';
import dotenv from 'dotenv';

import path from 'node:path';
import {fileURLToPath} from 'node:url';
import cookieParser from 'cookie-parser';
import usersRouter from './routes/index.js';
import pageRouter from './routes/page.js';
import logger from "log4js";
import {getDB, isBlzTokenExpired} from "./utils/Utils.js";
import cors from "cors";
import {getHsToken} from "./utils/hsapi.js";

dotenv.config();


const app = express();

// 配置log4js
logger.configure({
    appenders: {
        console: {type: 'console'},
        file: {type: 'file', filename: 'application.log'}
    },
    categories: {
        default: {appenders: ['file', 'console'], level: 'debug'}
    }
});


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

app.set('views', './views');
app.set('view engine', 'ejs');
app.use(cors())
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'), {maxAge: '1d'}));

app.use(async (req, res, next) => {
    logger.getLogger(`default`).debug(`[${req.method}] -- ${req.url}`)
    //  判断hsToken是否过期
    const db = await getDB()
    logger.getLogger(`hsToken Expired `).debug(`${isBlzTokenExpired(db.data.expiresIn)}`)
    if (isBlzTokenExpired(db.data.expiresIn)) {
        await getHsToken()
    }
    next()
})

app.use('/api', usersRouter);
app.use('/', pageRouter)

await getDB()

export default app